<template>
  <div class="contain">
    <div class="item">
      <div style="margin-bottom:5px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="primary" @click="handleDelete">删除</el-button>
        <el-button type="primary" @click="handleRefresh">刷新</el-button>
        <!-- <el-button type="primary" @click="handleEdit(scope.row.id,scope.$index)">编辑</el-button> -->
      </div>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        height="500"
        highlight-current-row
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        style="width: 100%"
        @row-click="selectionChangeHandle"
        @selection-change="handleMultipleSelect"
      >
        <el-table-column min-width="100" type="selection" />
        <el-table-column min-width="100" prop="intervalCode" label="区间编码">
          <template slot-scope="scope">
            <el-input v-if="scope.row.addFlag" v-model="scope.row.intervalCode" placeholder="请输入编码" />
            <span v-else>{{ scope.row.intervalCode }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="130" prop="intervalType" label="区间类型">
          <template slot-scope="scope">
            <span v-show="!scope.row.isEdit">  {{ formaterData(typeList,scope.row.intervalType) }}</span>
            <el-select
              v-show="scope.row.isEdit"
              v-model="scope.row.intervalType"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeList"
                :key="item.dictCode"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column min-width="90" prop="enable" label="启用状态">
          <template slot-scope="scope">
            <span v-show="!scope.row.isEdit">  {{ scope.row.enable?'启用':scope.row.enable===0?'停用':scope.row.enable }}</span>
            <el-select
              v-show="scope.row.isEdit"
              v-model="scope.row.enable"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in enableList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column min-width="140" prop="" label="操作">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.isEdit" type="text" @click.stop="handleEdit(scope.row,scope.$index)">编辑</el-button>
            <el-button v-else type="text" @click.stop="handleSave(scope.row,scope.$index)">保存</el-button>
            <el-button v-if="scope.row.isEdit" type="text" @click.stop="reFreshData(scope.row,scope.$index)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="item">
      <div style="margin-bottom:5px">
        <el-button type="primary" @click="handleAddItem">新增</el-button>
        <el-button type="primary" @click="handleDeleteChild">删除</el-button>
      </div>
      <el-table
        v-loading="childLoading"
        :data="childData"
        border
        highlight-current-row
        height="500"
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        style="width: 100%"
        @selection-change="handleMultipleSelect2"
      >
        <el-table-column min-width="100" type="selection" />
        <el-table-column min-width="80" prop="code" label="编码">
          <template slot-scope="scope">
            <el-input v-if="scope.row.addFlag" v-model="scope.row.code" placeholder="请输入编码" />
            <span v-else>{{ scope.row.code }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="130" prop="showValue" label="显示值">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.showValue" placeholder="请输入显示值" />
            <span v-else>{{ scope.row.showValue }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="130" prop="sort" label="顺序">
          <template slot-scope="scope">
            <el-input-number v-if="scope.row.isEdit" v-model="scope.row.sort" style="width:80%" />
            <span v-else>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="140" prop="" label="操作">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.isEdit" type="text" @click="handleEditItem(scope.row,scope.$index)">编辑</el-button>
            <el-button v-else type="text" @click="handleSaveItem(scope.row,scope.$index)">保存</el-button>
            <el-button v-if="scope.row.isEdit" type="text" @click="refreshChildData()">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { formaterData } from '@/utils'
import { getDictByPatchType } from '@/api/dataDict'
import { getAreaList, saveAreaList, getChildTableList, saveChildTableList, deleteBatch, deleteBatchChild } from '@/api/display/areaMatain'
export default {
  name: 'AreaMatain',
  data() {
    return {
      formaterData,
      activeCode: '',
      childLoading: false,
      tableLoading: false,
      tableSelected: [],
      tableSelected2: [], // 子表选中数据
      childData: [],
      tableData: [],
      typeList: [],
      enableList: [{ code: 1, name: '启用' }, { code: 0, name: '停用' }]
    }
  },
  async  created() {
    this.reFreshData()
    const { INTERVAL_TYPE } = await getDictByPatchType(['INTERVAL_TYPE'])
    this.typeList = INTERVAL_TYPE // 区间类型
  },
  methods: {
    refreshChildData() {
      this.childLoading = true
      getChildTableList(this.activeCode).then(res => {
        if (res.success) this.childData = res.data.records
        this.childLoading = false
      }).catch(() => {
        this.childLoading = false
      })
    },
    selectionChangeHandle(data) {
      // this.tableSelected = data
      this.activeCode = data.intervalCode
      if (this.activeCode) this.refreshChildData()
      // console.log('哈哈哈', data)
    },
    reFreshData() {
      this.tableLoading = true
      getAreaList().then(res => {
        if (res.success) this.tableData = res.data
        // this.activeCode = ''
        // this.childData = []
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleSave(data, index) {
      if (!data.intervalCode || !data.intervalType) {
        this.$message.warning('请完善新增数据')
        return
      }
      saveAreaList(data).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.tableData[index].isEdit = false
        }
      })
    },
    handleSaveItem(data, index) {
      if (!data.code || !data.showValue) {
        this.$message.warning('请完善新增数据')
        return
      }
      saveChildTableList(data).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.childData[index].isEdit = false
          this.refreshChildData()
        }
      })
    },
    handleAdd() {
      const data = { isEdit: true, addFlag: Math.floor(Math.random() * 0xffffff).toString(16), intervalCode: '', intervalType: '', enable: 1 }
      this.tableData.unshift(data)
    },
    // 主表删除
    handleDelete() {
      if (!this.singleJudge(this.tableSelected, '删除', false)) {
        return
      }
      const ids = this.tableSelected.map(v => v.id)
      deleteBatch(ids).then(res => {
        if (res.success) {
          this.$message.warning('删除成功')
          this.reFreshData()
        }
      })
    },
    // 子表删除
    handleDeleteChild() {
      if (this.tableSelected2.length === 0) {
        this.$message({
          showClose: true,
          type: 'warning',
          duration: 800,
          message: '请先选择主表数据'
        })
        return
      }
      const ids = this.tableSelected2.map(v => v.id)
      deleteBatchChild(ids).then(res => {
        if (res.success) {
          this.$message.warning('删除成功')
          this.refreshChildData()
        }
      })
    },
    handleMultipleSelect(data) {
      this.tableSelected = data
    },
    handleMultipleSelect2(data) {
      this.tableSelected2 = data
    },
    handleAddItem() {
      if (!this.activeCode) {
        this.$message({
          showClose: true,
          type: 'warning',
          duration: 800,
          message: '请先选择主表数据'
        })
        return
      }
      const data = { sort: this.childData.length + 1, intervalCode: this.activeCode, isEdit: true, addFlag: Math.floor(Math.random() * 0xffffff).toString(16), code: '', showValue: '' }
      this.childData.push(data)
    },
    handleEdit(data, index) {
      // if (!this.singleJudge(this.tableSelected, '编辑', true)) {
      //   return
      // }
      this.$set(this.tableData[index], 'isEdit', true)
    },
    handleEditItem(data, index) {
      this.$set(this.childData[index], 'isEdit', true)
    },
    handleRefresh() {
      this.reFreshData()
      this.childData = []
      this.activeCode = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.contain{
  display:flex;
  justify-content: space-between;
  .item{
    width: 49%;
  }
}
</style>
